package com.yilin.tms.capital.service.impl;


import com.google.gson.reflect.TypeToken;
import com.yilin.tms.capital.commons.wechat.WeChatTradeRecord;
import com.yilin.tms.capital.service.ITradeRecordService;
import com.yilin.tms.capital.service.IWeCartService;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.MapUtil;
import com.yilin.tms.core.application.PlatRequest;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.capital.TradeRecord;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.hatch.HatchPlatProduct;
import com.yilin.tms.core.remote.IOrderRemote;
import com.yilin.tms.core.remote.IUserRemote;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class WeCartService implements IWeCartService {
    private Logger logger = LoggerFactory.getLogger(WeCartService.class);
    @Resource
    IUserRemote userRemote;
    @Resource
    ITradeRecordService tradeRecordService;
    @Resource
    IOrderRemote orderRemote;

    public static void main(String[] args) {

    }



    @Override
    public Map<String, Object> wxChartAppTransactions(Account loginUser, TradeRecord tradeRecord,String trminalType) {
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatch(tradeRecord.getPlatId()));
        Map<String,Object>  map= PlatRequest.request(loginUser.getToken(), platProduct.getNetworkFreightUrl() + "/platform/weChat/tradePaymentOrder", MapUtil.generate(paramMap -> {
            paramMap.put("tradeNo", tradeRecord.getTradeNo());
            paramMap.put("tradeName", tradeRecord.getTransName());
            paramMap.put("outOrganizeId", tradeRecord.getPaymentOrganizeId().replace("（个体）",""));
            paramMap.put("outAcctName", tradeRecord.getPaymentOrganizeName());
            paramMap.put("inOrganizeId", tradeRecord.getIncomeOrganizeId());
            paramMap.put("inAcctName", tradeRecord.getIncomeOrganizeId().replace("（个体）",""));
            paramMap.put("tranAmount", tradeRecord.getMoney());
            paramMap.put("remark", tradeRecord.getRemark());
            paramMap.put("userType",loginUser.getUserType());
            paramMap.put("trminalType", trminalType);
        }), new TypeToken<Map<String,Object>>() {});
        ParamUtil.isNull(map,"微信平台服务器返回数据为空");
        tradeRecord.setInitiateTime(new Date());
        tradeRecord.setOptUserId(loginUser.getId());
        tradeRecord.setOptUserName(loginUser.getName());
        tradeRecord.setInitiateTime(new Date());
        tradeRecord.setPayType(TradeRecord.PayType.wxPay);
        tradeRecord.setBankType(TradeRecord.BankType.none);
        tradeRecordService.saveOrUpdate(tradeRecord);
        return map;
    }
    /**
     * 支付宝支付：交易结果查询
     * 备注：调这个方法之后需要掉用订单通知接口
     */
    @Override
    public TradeRecord queryWeChatPayOrder(Account loginUser, TradeRecord tradeRecord ) {
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatch(tradeRecord.getPlatId()));
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("tradeNo", tradeRecord.getTradeNo());
        WeChatTradeRecord weChatTradeRecord= PlatRequest.request(loginUser.getToken(), platProduct.getNetworkFreightUrl() + "/platform/weChat/wxChartAppQueryTransactions",paramMap, new TypeToken<WeChatTradeRecord>() {});
        ParamUtil.isNull(weChatTradeRecord,"微信查询平台服务器返回数据为空");
        if (tradeRecord.getBankFlowNo() == null) tradeRecord.setBankFlowNo(weChatTradeRecord.getBankFlowNo());
        if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.success) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.paySuccess);
            tradeRecord.setFinishTime(weChatTradeRecord.getCompleteTime());
        } else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.handle) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.wait);
        } else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.close) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.close);
        }else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.fail) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.payFail);
        }else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.notpay) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.create);
        }
        if(weChatTradeRecord.getBankMsg()!=null)tradeRecord.setTradeFailMsg(weChatTradeRecord.getBankMsg());
        if(tradeRecord.getPaymentCapitalAccount()==null)tradeRecord.setPaymentCapitalAccount(weChatTradeRecord.getOutAcctNo());
        if(tradeRecord.getIncomeCapitalAccount()==null)tradeRecord.setIncomeCapitalAccount(weChatTradeRecord.getInAcctNo());
        tradeRecordService.saveOrUpdate(tradeRecord);
        return  tradeRecord;
    }
    @Override
    public TradeRecord weChatRefund(Account loginUser, TradeRecord tradeRecord) {
        tradeRecord.setPayType(TradeRecord.PayType.wxPay);
        if (tradeRecord.getOriginalPaymentOrderId() == null) throw new BusinessException("原交易单ID为空");
        TradeRecord originalTradeRecord = tradeRecordService.getTradeRecordById(tradeRecord.getOriginalPaymentOrderId());
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatch(tradeRecord.getPlatId()));
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("tradeNo", tradeRecord.getTradeNo());
        paramMap.put("tradeName", tradeRecord.getTransName());
        paramMap.put("outOrganizeId", tradeRecord.getPaymentOrganizeId().replace("（个体）",""));
        paramMap.put("outAcctName", tradeRecord.getPaymentOrganizeName());
        paramMap.put("inOrganizeId", tradeRecord.getIncomeOrganizeId());
        paramMap.put("inAcctName", tradeRecord.getIncomeOrganizeId().replace("（个体）",""));
        paramMap.put("tranAmount", tradeRecord.getMoney());
        paramMap.put("remark", tradeRecord.getRemark());
        paramMap.put("refundOriginalTradeNo", originalTradeRecord.getTradeNo());
        WeChatTradeRecord weChatTradeRecord= PlatRequest.request(loginUser.getToken(), platProduct.getNetworkFreightUrl() + "/platform/weChat/wxChartAppRefund",paramMap, new TypeToken<WeChatTradeRecord>() {});
        tradeRecord.setInitiateTime(weChatTradeRecord.getInitiateTime());
        if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.success) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.paySuccess);
        } else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.handle) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.wait);
        } else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.close) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.close);
        }else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.fail) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.payFail);
        }else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.notpay) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.create);
        }
        tradeRecord.setBankFlowNo(weChatTradeRecord.getBankFlowNo());
        if(weChatTradeRecord.getBankMsg()==null)tradeRecord.setTradeFailMsg(weChatTradeRecord.getBankMsg());
        tradeRecordService.saveOrUpdate(tradeRecord);
        return  tradeRecord;
    }
    @Override
    public TradeRecord weChatRefundQuery(Account loginUser, TradeRecord tradeRecord) {
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatch(tradeRecord.getPlatId()));
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("tradeNo", tradeRecord.getTradeNo());
        WeChatTradeRecord weChatTradeRecord= PlatRequest.request(loginUser.getToken(), platProduct.getNetworkFreightUrl() + "/platform/weChat/wxChartAppQueryRefund", paramMap, new TypeToken<WeChatTradeRecord>() {});
        ParamUtil.isNull(weChatTradeRecord,"微信查询平台服务器返回数据为空");
        if (weChatTradeRecord.getBankFlowNo() == null) tradeRecord.setBankFlowNo(weChatTradeRecord.getBankFlowNo());
        if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.success) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.paySuccess);
            tradeRecord.setFinishTime(weChatTradeRecord.getCompleteTime());
        } else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.handle) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.wait);
        } else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.close) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.close);
        }else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.fail) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.payFail);
        }else if (weChatTradeRecord.getWeChatTradeStatus()== WeChatTradeRecord.WeChatTradeStatus.notpay) {
            tradeRecord.setTradeStatus(TradeRecord.TradeStatus.create);
        }
        if(weChatTradeRecord.getBankMsg()!=null)tradeRecord.setTradeFailMsg(weChatTradeRecord.getBankMsg());
        if(tradeRecord.getPaymentCapitalAccount()==null)tradeRecord.setPaymentCapitalAccount(weChatTradeRecord.getOutAcctNo());
        if(tradeRecord.getIncomeCapitalAccount()==null)tradeRecord.setIncomeCapitalAccount(weChatTradeRecord.getInAcctNo());
        tradeRecordService.saveOrUpdate(tradeRecord);
        return  tradeRecord;
    }


}

